﻿// <copyright project="Salient.SqlServer" file="HierarchyIdTypeConverter.cs" company="Sky Sanders">
// This source is a Public Domain Dedication.
// Please see http://spikes.codeplex.com/ for details.   
// Attribution is appreciated
// </copyright> 
// <version>1.0</version>
using System;
using System.ComponentModel;
using System.Globalization;
using Microsoft.SqlServer.Types;

namespace Salient.SqlServer.Types
{
    public class HierarchyIdTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof (string) || sourceType == typeof (SqlHierarchyId))
            {
                return true;
            }

            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof (string) || destinationType == typeof (SqlHierarchyId))
            {
                return true;
            }

            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                return new HierarchyId((string) value);
            }
            if (value is SqlHierarchyId)
            {
                return new HierarchyId((SqlHierarchyId) value);
            }
            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
                                         Type destinationType)
        {
            if (destinationType == typeof (string))
            {
                return value.ToString();
            }

            if (destinationType == typeof (SqlHierarchyId))
            {
                return ((HierarchyId) value).Inner;
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }

        public override bool IsValid(ITypeDescriptorContext context, object value)
        {
            if (value is string)
            {
                try
                {
                    SqlHierarchyId.Parse((string) value);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            if (value is SqlHierarchyId)
            {
                return true;
            }

            return base.IsValid(context, value);
        }
    }
}